package com.zego.wawaji.third.auth;

import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;

import com.noble.library.basic.log.PLogger;
import com.zego.wawaji.base.module.ModuleMgr;
import com.zego.wawaji.base.toast.PToast;
import com.zego.wawaji.ui.UIShow;
import com.zego.wawaji.ui.bean.LoginResult;
import com.zego.wawaji.ui.bean.user.EditKey;
import com.zego.wawaji.ui.dialog.LoadingDialog;
import com.zego.wawaji.wawaji_client.AppTinkerLike;

import java.util.HashMap;

/**
 * 三方结果回调
 * Created by Su on 2017/10/13.
 */
public class OauthBack implements OauthCallback {
    private FragmentActivity activity;

    public OauthBack(FragmentActivity activity) {
        this.activity = activity;
    }

    @Override
    public void onSuccess(int platform, final ThirdInfo user) {
        PLogger.d("Third---onSuccess: " + platform + " " + user);

        LoadingDialog.show(activity, "正在登录");
        final String openid = user.getOpenid();
        ModuleMgr.getLoginMgr().weChatLogin(openid, user.getUnionid(), response -> LoadingDialog.closeLoadingDialog(200, () -> {
            PToast.showShort(response.getMsg());
            if (!response.isOk()) return;

            LoginResult data = (LoginResult) response.getBaseData();
            ModuleMgr.getLoginMgr().setCookie(data.getAuth());
            ModuleMgr.getLoginMgr().putAllLoginInfo(data.getUid(), true);
            UIShow.showMainClearTask(AppTinkerLike.activity);
            if (data.isNew()) {
                AppTinkerLike.isNewUser = true;

                // 设置微信昵称为个人昵称
                if (user != null && !TextUtils.isEmpty(user.getNickName())) {
                    ModuleMgr.getCenterMgr().reqMyInfo(response1 -> {
                        if (!response1.isOk()) return;
                        String name = user.getNickName();
                        if (TextUtils.isEmpty(name)) {
                            name = "默认昵称";
                        }
                        HashMap<String, Object> postParams = new HashMap<>();
                        postParams.put(EditKey.s_key_nickName, name);
                        postParams.put(EditKey.s_key_avatar, user.getAvatar());
                        ModuleMgr.getCenterMgr().updateMyInfo(postParams, null);
                    });
                }
            }
        }));
    }

    @Override
    public void onFailure(int platform, String msg) {
        PLogger.d("Third----onFailure: " + platform + " " + msg);
        LoadingDialog.closeLoadingDialog();
        PToast.showShort("登录失败");
    }

    @Override
    public void onCancelled(int platform) {
        PLogger.d("Third----取消登录: " + platform);
        LoadingDialog.closeLoadingDialog();
    }

    @Override
    public void onError(int platform, Exception ex) {
        PLogger.d("Third----onError: msg: " + platform);
        LoadingDialog.closeLoadingDialog();
        PToast.showShort("登录失败");
    }
}
